package com.ruiben.mall.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruiben.mall.impl.AttributeServiceImpl;
import com.ruiben.mall.impl.ProductServiceImpl;
import com.ruiben.mall.pojo.*;
import com.ruiben.mall.utils.CommonJSONResult;
import com.ruiben.mall.utils.PagedResult;
import com.ruiben.mall.utils.StringUtil;
import com.ruiben.mall.vo.AttributeVo;
import com.ruiben.mall.vo.SpecBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Example;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.ruiben.mall.config.Config.BASE_URL;
import static com.ruiben.mall.config.Config.ENABLE_STATE;
import static com.ruiben.mall.config.ErrorConfig.ID_NOT_EMPTY_CODE;
import static com.ruiben.mall.config.ErrorConfig.ID_NOT_EMPTY_MSG;
import static com.ruiben.mall.controller.BaseController.PAGE_SIZE;

@RestController
@RequestMapping("product")
@Api(value = "商品业务相关的接口", tags = {"商品业务相关的controller"})
public class ProductController {

    @Autowired
    private ProductServiceImpl productService;

    @Autowired
    private AttributeServiceImpl attributeService;




    @ApiOperation(value = "获取所有商品分类", notes = "获取所有商品分类")
    @PostMapping(value = "getProductCategoryList")
    public CommonJSONResult getProductCategoryList() {
        List<ProductCategory> productCategory = productService.getProductCategory();
        for (ProductCategory category:productCategory){
            if (StringUtils.isNotBlank(category.getImagePath())){
                category.setImagePath(BASE_URL + category.getImagePath());
            }
        }
        return CommonJSONResult.ok(productCategory);
    }


    @PostMapping("getParentCategory")
    public CommonJSONResult getParentCategory(){
        List<ProductCategory> parentProductCategory = productService.getParentProductCategory();
        for (ProductCategory category:parentProductCategory){
            if (StringUtils.isNotBlank(category.getImagePath())){
                category.setImagePath(BASE_URL + category.getImagePath());
            }
        }
        return CommonJSONResult.ok(parentProductCategory);
    }

    @PostMapping("getChildCategory")
    public CommonJSONResult getChildCategory(String cateId){
        if (StringUtils.isBlank(cateId)){
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }
        List<ProductCategory> parentProductCategory = productService.getChildProductCategory(cateId);
        return CommonJSONResult.ok(parentProductCategory);
    }

    /**
     * 获取所有商品列表
     *
     * @return
     */
    @PostMapping("getProductList")
    public CommonJSONResult getProductList(Integer page) {
        if (page == null) {
            page = 1;
        }
        PagedResult productList = productService.getProductList(page, PAGE_SIZE);

        return CommonJSONResult.ok(productList);

    }


    /**
     * 获取单个商品详情
     */
    @PostMapping("getProductDetail")
    public CommonJSONResult getProducyDetailById(String id) {

        if (StringUtils.isBlank(id)){
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        ShopProduct product = productService.getProductById(id);

        if (product != null) {
            product.setImagePath(BASE_URL + product.getImagePath());
            if (product.getCollNum() == null) {
                product.setCollNum(0);
            }

            List<ProductPhoto> productImages =
                    productService.getProductImagesByProductId(product.getId());

            for (int i = 0; i < productImages.size(); i++) {
                String imagePath = productImages.get(i).getImagePath();
                String s = imagePath.replaceAll("\\\\", "/");
                productImages.get(i).setImagePath(BASE_URL + s);
            }
            product.setImageList(productImages);

            //获取该商品的唯一所有属性值
            List<ProductAttr> productAttrList = productService.getProductAttrList(id);


            //获取typeid
            String typeId = "";
            if (productAttrList != null && productAttrList.size() > 0) {
                typeId = productAttrList.get(0).getAttribute().getTypeId();
            }

            //获取商品的规格列表
            List<ProductAttr> productSpecrList = productService.getSpecList(id);
            if (StringUtils.isBlank(typeId)){
                if (productSpecrList != null && productSpecrList.size() > 0) {
                    typeId = productSpecrList.get(0).getAttribute().getTypeId();
                }
            }

            List<Attribute> attributes = new ArrayList<>();
            List<Attribute> attributeList1 = attributeService.getAttributeList(typeId,1);
            List<Attribute> attributeList2 = attributeService.getAttributeList(typeId,2);

            attributes.addAll(attributeList1);
            attributes.addAll(attributeList2);

            List<SpecBean> specBeans= new ArrayList<>();
            for (Attribute attribute:attributes){
                SpecBean specBean = new SpecBean();
                List<SpecBean.ChildrenBean> childrenBeans = new ArrayList<>();
                if (productSpecrList != null && productSpecrList.size()>0){

                    for (ProductAttr productAttr:productSpecrList){
                        if (attribute.getId().equals(productAttr.getAttrId())){
                            SpecBean.ChildrenBean childrenBean = new SpecBean.ChildrenBean();
                            childrenBean.setTypeId(productAttr.getAttrId());
                            childrenBean.setId(productAttr.getId());
                            childrenBean.setValueStr(productAttr.getAttrValue());
                            childrenBean.setPrice(productAttr.getAttrPrice().toString());
                            String id1 = productAttr.getAttrId();
                            Attribute attributeById = attributeService.getAttributeById(id1);
//                        String replace = attributeById.getAttrValues().replace("\r\n", ",");
//                        childrenBean.setAttrValues(replace);
                            String[] split = attributeById.getAttrValues().split("\r\n");
                            childrenBean.setValues(Arrays.asList(split));
                            childrenBeans.add(childrenBean);
                        } else {
                            SpecBean.ChildrenBean childrenBean = new SpecBean.ChildrenBean();
                            specBean.setAttrInputType(attribute.getAttrInputType());
                            childrenBean.setValues(attribute.getValues());
                            childrenBean.setTypeId(attribute.getId());
                            specBean.setLabel(attribute.getAttrName());
                            childrenBeans.add(childrenBean);
                        }
                    }

                    specBean.setAttrInputType(attribute.getAttrInputType());
                    specBean.setId(attribute.getId());
                    specBean.setLabel(attribute.getAttrName());
                    specBean.setChildren(childrenBeans);
                } else {
                    SpecBean.ChildrenBean childrenBean = new SpecBean.ChildrenBean();
                    specBean.setAttrInputType(attribute.getAttrInputType());
                    childrenBean.setValues(attribute.getValues());
                    childrenBean.setTypeId(attribute.getId());
                    specBean.setLabel(attribute.getAttrName());
                    childrenBeans.add(childrenBean);
                    specBean.setChildren(childrenBeans);
                }

                specBeans.add(specBean);
            }

            for (SpecBean specBean:specBeans){
                List<SpecBean.ChildrenBean> children = specBean.getChildren();
                HashSet hashSet = new HashSet(children);
                children.clear();
                children.addAll(hashSet);
                specBean.setChildren(children);
            }


            List<SpecBean> specBeansVos = new ArrayList<>();
            for (int i =0;i<specBeans.size();i++){
                SpecBean specBean = specBeans.get(i);
                List<SpecBean.ChildrenBean> children = specBean.getChildren();
                List<SpecBean.ChildrenBean> childrenBeans = new ArrayList<>();
                int num = 0;
                for (int j=0;j<children.size();j++){
                    if (!StringUtils.isBlank(children.get(j).getId())){
                        childrenBeans.add(children.get(j));
                    } else {

                        num ++;
                    }
                }

                if (num == children.size()){
                    childrenBeans.add(children.get(0));
                }
                specBean.setChildren(childrenBeans);
                specBeansVos.add(specBean);

            }

            product.setSpecVo(specBeansVos);
            product.setProductAttrs(productAttrList);


            return CommonJSONResult.ok(product);
        } else {
            return CommonJSONResult.errorMsg("没有对应的商品");
        }
    }



    /**
     * 获取商品所有类型
     *
     * @return
     */
    @PostMapping("getProductTypeList")
    public CommonJSONResult getProductTypeList() {
        List<ProductType> productTypeList = productService.getProductTypeList();
        if (productTypeList != null && productTypeList.size() > 0) {
            return CommonJSONResult.ok(productTypeList);
        } else {
            return CommonJSONResult.errorMsg("暂无数据");
        }
    }


    /**
     * 根据分类获取商品
     * @param cateId
     * @return
     */
    @PostMapping("getProductListForCate")
    public CommonJSONResult getProductListForCate(String cateId,Integer sort){

        if (sort == null){
            sort = 1;
        }

        if (StringUtils.isBlank(cateId)){
            return CommonJSONResult.errorMsg("分类id不能为空");
        }

        List<ShopProduct> productListByCate = productService.getProductListByCate(cateId,sort);
        for (ShopProduct product:productListByCate){
            product.setImagePath(BASE_URL + product.getImagePath());
        }
        return CommonJSONResult.ok(productListByCate);
    }



    /**
     * 根据分类获取商品
     * @param cateId
     * @return
     */
    @PostMapping("getProductListForPriceSort")
    public CommonJSONResult getProductListForPriceSort(String cateId,Integer sort){

        if (sort == null){
            sort = 1;
        }

        if (StringUtils.isBlank(cateId)){
            return CommonJSONResult.errorMsg("分类id不能为空");
        }

        List<ShopProduct> productListByCate = productService.getProductListByPriceSort(cateId,sort);
        for (ShopProduct product:productListByCate){
            product.setImagePath(BASE_URL + product.getImagePath());
        }
        return CommonJSONResult.ok(productListByCate);
    }

    @PostMapping("getProductListBySolesSort")
    public CommonJSONResult getProductListBySolesSort(String cateId,Integer sort){

        if (sort == null){
            sort = 1;
        }

        if (StringUtils.isBlank(cateId)){
            return CommonJSONResult.errorMsg("分类id不能为空");
        }

        List<ShopProduct> productListByCate = productService.getProductListBySolesSort(cateId,sort);
        for (ShopProduct product:productListByCate){
            product.setImagePath(BASE_URL + product.getImagePath());
        }
        return CommonJSONResult.ok(productListByCate);
    }


    @PostMapping("getProductListByNewSort")
    public CommonJSONResult getProductListByNewSort(String cateId,Integer sort){

        if (sort == null){
            sort = 1;
        }

        if (StringUtils.isBlank(cateId)){
            return CommonJSONResult.errorMsg("分类id不能为空");
        }

        List<ShopProduct> productListByCate = productService.getProductListByNewSort(cateId,sort);
        for (ShopProduct product:productListByCate){
            product.setImagePath(BASE_URL + product.getImagePath());
        }
        return CommonJSONResult.ok(productListByCate);
    }


}
